import Vue from 'vue'
import Vuex from 'vuex'
import {TOKEN_KEY, setToken, getToken, getUserInfo} from "@/static/js/util.js"
import apiRequest from '@/static/js/api.request.js'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		forcedLogin: true, //是否强制登录
		hasLogin: getToken() ? true : false,
		token: getToken(),
		userInfo: getUserInfo()
	}, 
	mutations: {
		setToken (state, token) {
			state.token = token
			if(token){
				state.hasLogin = true
			}else{
				state.hasLogin = false
			}
			setToken(token)
		},
		setUserInfo (state, userInfo) {
			state.userInfo = userInfo
			uni.setStorageSync(TOKEN_KEY + 'UserInfo', userInfo)
		},
		login (state, payload) {
			let vm = this;
			uni.showLoading({title: '请稍候', mask: true})
			apiRequest({ url: 'api/login', data: payload.userInfo, method: 'POST' }).then(res => {
				uni.hideLoading()
				if (res.code) {
					vm.commit('setUserInfo', res.data);
					vm.commit('setToken', res.data.LoginToken);
					if(payload.callBackFn){
						return payload.callBackFn(res);
					}
				} else {
					uni.showToast({icon: 'none', title: res.msg});
				}
			})
		},
		logout (state, payload) {
			let vm = this;
			uni.showLoading({title: '请稍候', mask: true})
			apiRequest({ url: 'api/logout' }).then(res => {
				uni.hideLoading()
				if (res.code) {
					vm.commit('setToken', '')
					vm.commit('setUserInfo', {})
					if(payload && payload.callBackFn){
						return payload.callBackFn(res);
					}
				} else {
					uni.showToast({icon: 'none', title: res.msg});
				}
			})
		}
	}
})

export default store
